/*********************************************************************************
 *      Copyright:  (C) 2021 litupei<lismilepei@163.com>
 *                  All rights reserved.
 *
 *       Filename:  prj_ds18b20.h
 *    Description:  This file is prj_ds18b20.h
 *                 
 *        Version:  1.0.0(2021年08月03日)
 *         Author:  litupei <lismilepei@163.com>
 *      ChangeLog:  1, Release initial version on "2021年08月03日 16时23分47秒"
 *                 
 ********************************************************************************/

#include "prj_ds18b20.h"

/*获取ds18b20的温度值*/
int ds18b20_temp(float *temp)
{
	int		fd = -1;
	int		rv = 0, rv1 = -1;
	DIR		*dirp;
	struct dirent	*direntp;
	char		path[255] = "/sys/bus/w1/devices/";
	char		buf[512];
	char		*ptr;
	memset(buf, 0, sizeof(buf));
	/* 打开dir文件夹 */
	if((dirp = opendir(path)) == NULL)
	{
		printf("opendir %s error: %s\n", path, strerror(errno));
		return -1;
	}

	/* 列出dir里面的所有文件和文件夹 */
	while((direntp = readdir(dirp)) != NULL)
	{
		//printf("Find file: %s\n", direntp->d_name);
		if(strstr(direntp->d_name, "28-"))
		{
			//printf("Find file: %s\n", direntp->d_name);
			strncat(path, direntp->d_name, sizeof(direntp->d_name));
			//strncpy(dir_name, direntp->d_name, sizeof(dir_name));
			strncat(path,"/w1_slave",sizeof(path)-strlen(path));
			rv = 1;
		}
	}

	closedir(dirp);
	if(!rv)
	{
		printf("cann't find the dir[%s]: %s \n", path, strerror(errno));
		return -2;
	}
	//printf("the path is : %s \n", path);

	fd = open(path, O_RDONLY);
	if(fd < 0)
	{
		printf("open the file failure : %s \n", strerror(errno));
		return -3;
	}	

	if((rv1 = read(fd, buf, sizeof(buf))) < 0 )
	{
		printf("read the data from file[%s] failure: %s \n", path, strerror(errno));
		close(fd);
		return -4;
	}
	lseek(fd, 0, SEEK_SET);

	while(rv1 = read(fd, buf, rv1))
	{
		//printf("%s",buf);
		ptr = strstr(buf, "t=");
		if(!ptr)
		{
			printf("Cann't get the temp!");
			return -5;
		}
		ptr +=2;
		*temp = atof(ptr)/1000.0;
	}

	close(fd);
	
	return 0;
}
